package com.ruoyi.job.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.google.gson.JsonObject;
import com.ruoyi.job.config.EmailUtil;
import com.ruoyi.job.config.PhoneUtil;
import com.ruoyi.job.service.AsyncMainService;
import com.ruoyi.system.api.RemoteTcwAppliService;
import com.ruoyi.system.api.TcwPayService;
import com.ruoyi.system.api.domain.SysTCwAppli;
import com.ruoyi.system.api.domain.SysTCwPaymentPlan;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.utils.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{
    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    /**
     * 微信测试账号推送
     */
    public void push() throws InterruptedException {
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId("wx34bf37123ff23c52");
        wxStorage.setSecret("8494f57dbe9bf33839092f91b0e28f66");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        //获取所有关注测试号的用户openId
        List<String> wechatAllUser = getWechatAllUser();

        //实现了多人推送
        wechatAllUser.forEach(openId -> {
            //2,推送消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(openId)//要推送的用户openid

                    .templateId("fo5llzoOU8-bNMMizypzigWrsnJkZaf8wXVtA7f1l_g")//模版id
                    .url("https://baidu.com/")//点击模版消息要访问的网址
                    .build();
            //3,如果是正式版发送模版消息，这里需要配置你的信息
            //        templateMessage.addData(new WxMpTemplateData("name", "value", "#FF00FF"));
            //                templateMessage.addData(new WxMpTemplateData(name2, value2, color2));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            } catch (Exception e) {
                System.out.println("推送失败：" + e.getMessage());
                e.printStackTrace();
            }
        });
    }
    /**
     * 获取所有关注测试号的用户openId
     */
    private List<String> getWechatAllUser() {
        String tokenObject = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx34bf37123ff23c52&secret=8494f57dbe9bf33839092f91b0e28f66");
        JSONObject jsonObject = JSONUtil.parseObj(tokenObject);
        String access_token =(String) jsonObject.get("access_token");

        System.out.println("=========获取所有用户的openid====token=========="+access_token);
        String AllUser =  HttpUtil.get("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token ) ;
        Map<String, Object> getUser_result = JSON.parseObject(AllUser);
        Map<String, Object> result = (Map<String, Object>) getUser_result.get("data");
        List<String> userList = null;
        if(!"".equals(result.get("count"))){
            userList =  (List<String>) result.get("openid");
        }

        return userList;
    }
    @Resource
    TcwPayService tcwPayService;
    @Autowired
    RemoteTcwAppliService remoteTcwAppliService;
    /**
     * 定时跑批
     */
    public void alipayClient() throws AlipayApiException {
        List<SysTCwPaymentPlan> openFegin = tcwPayService.getOpenFegin();
        for (SysTCwPaymentPlan tCwPaymentPlan : openFegin) {
           if(tCwPaymentPlan.getReserve1()!=null){
               String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSJw9FwYMhvbQNbfjNAoDoO9Sc6asBCesu9dGB0BEpE82rPCsr6BRpjqPZMl2NRl3nV2FZtbgQafOT+vmZqhBhj8xPZTwoFdmyuZSOmig+2GdFuraYzGqa/Xt9Efy3kZVk7/551P9wfr33lBCqvXqN4QOQ7qA4oXfxZkes1lJrivYDsjPPtfPoHL1vme1FZKiHRgyxyjULhGeh2WpLBMtaRFl/u1lWI9mXg6TpOUM7TzXDn3tp5DizBFKPbH1AcjkrQVEsE/Bry8C2w2XZAYO1pZniL5O0JpQqn6148TxX+ru69lmJ6i2N6vy+kQRrBbq+zLNh8b/UcA0uhfP4+ShbAgMBAAECggEBAJ03tXhFJhom9r2ZSSnuNowGvq/JLDJxvi16n4sTItNtSk9Riyak0CiMGs4RnOVlADljKKRZi2NUMHLDrtmj3e9vCbVYEiIW/q9zoMzyTSt+7/u9jH9RZmufOTQ/MaYPVwmVdfalP5hkaS//6FwjtrzP2sAhlWHognfpQbPu/ugOSUe/mGSfGSB6hAVYlGvMTTkeEyPwza6AFa5hgZE9eYD6rK4Wa6hy3Td3LCVR8GBoFhHSo6pYvycchu77xfsSWvuHzj4/ew2o3go0nW3L+AjIIgLv2A0RSxoFzXb1THAKWCaBRlijJu+bsQRfALlipc4At9VO9obSL307lS497UkCgYEA8r+gBFo1qyZg2A4gJbaTcK/o0tKb+MiJshh0crBwDcCOBIyhlTCmDYjv5tmJVCLrllZ8bBYV+51Y1Koc6Z9ZcJumb9bb3KZoo+b2uoFb8YkJUV4rtqB4rNhCJWAaQa8uIHNMrjKtlq0G9NjI4uhjXb2QG3ZQeSxNeKJrCdvc8/cCgYEA3Z/pL6w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1S5VYW7JjQIDAQAB";
               AlipayConfig alipayConfig = new AlipayConfig();
               alipayConfig.setServerUrl("https://openapi.alipaydev.com/gateway.do");
               //id
               String reserve1 = tCwPaymentPlan.getReserve1();
               alipayConfig.setAppId("2021000121697244");
               alipayConfig.setPrivateKey(privateKey);
               alipayConfig.setFormat("json");
               alipayConfig.setAlipayPublicKey(alipayPublicKey);
               alipayConfig.setCharset("UTF8");
               alipayConfig.setSignType("RSA2");
               AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
               AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
               AlipayTradeQueryModel model = new AlipayTradeQueryModel();
               model.setOutTradeNo(reserve1);
               request.setBizModel(model);
               AlipayTradeQueryResponse response = alipayClient.execute(request);
               if (response.isSuccess()) {
                   //json格式化
                   JSONObject body = JSONUtil.parseObj(response.getBody());
                   Object alipay_trade_query_response = body.getObj("alipay_trade_query_response");
                   JSONObject entries = JSONUtil.parseObj(alipay_trade_query_response);
                   Object trade_status = entries.get("trade_status");
                   if(trade_status.equals("TRADE_SUCCESS")){
                       //获取json中的数据
                       Object code = entries.get("code");
                       Object msg = entries.get("msg");
                       Object buyer_logon_id = entries.get("buyer_logon_id");
                       Object buyer_user_id = entries.get("buyer_user_id");
                       Object buyer_user_type = entries.get("buyer_user_type");
                       Object out_trade_no = entries.get("out_trade_no");
                       Object send_pay_date = entries.get("send_pay_date");
                       Object total_amount = entries.get("total_amount");
                       Object trade_no = entries.get("trade_no");
                       //创建支付宝跑批类
                       SysTCwAppli sysTCwAppli = new SysTCwAppli();
                       sysTCwAppli.setCode((String) code);
                       sysTCwAppli.setMsg((String) msg);
                       sysTCwAppli.setBuyerLogonId((String) buyer_logon_id);
                       sysTCwAppli.setBuyerUserId((String) buyer_user_id);
                       sysTCwAppli.setBuyerUserType((String) buyer_user_type);
                       sysTCwAppli.setOutTradeNo((String) out_trade_no);
                       sysTCwAppli.setSendPayDate(DateUtil.parse((String) send_pay_date));
                        //转换类型
                       BigDecimal bigDecimal = NumberUtils.createBigDecimal((String) total_amount);
                       sysTCwAppli.setTotalAmount(bigDecimal);
                       sysTCwAppli.setTradeNo((String) trade_no);
                       sysTCwAppli.setTradeStatus((String) trade_status);
                       sysTCwAppli.setCode((String) code);
                       System.err.println(sysTCwAppli);
                       remoteTcwAppliService.add(sysTCwAppli);
                       System.err.println("回调成功");
                   }
               } else {
                   System.out.println("调用失败");
               }
           }
        }
    }








    @Autowired
    EmailUtil emailUtil;
    @Autowired
    PhoneUtil phoneUtil;
    @Autowired
    private AsyncMainService asyncMainService;
/*    @Autowired
    ExecutorConfig executorConfig;*/
    /**
     * 多线程
     */
    public  void send(){
       /* asyncMainService.executeAsync("q");
        asyncMainService.executeAsync("w");
        asyncMainService.executeAsync("e");*/
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        String email="2262665149@qq.com";
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                emailUtil.sendEmail(email,"线程","");
            }
        });
        String phone="17713069121";
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                phoneUtil.send(phone);
            }
        });

        executorService.shutdown();
    }

    public void async() {

    }
    public static void main(String[] args) {








       /* EmailUtil emailUtil = new EmailUtil();
        PhoneUtil phoneUtil = new PhoneUtil();

        ArrayList<User> list = new ArrayList<>();
        User user1 = new User();
        user1.setId(1);
        user1.setName("张三");
        user1.setEmail("2262665149@qq.com");
        user1.setPhone("17713069121");
        list.add(user1);

        User user2 = new User();
        user2.setId(1);
        user2.setName("李四");
        user2.setEmail("33333@qq.com");
        user2.setPhone("33333");
        list.add(user2);
        // 创建一个线程池，初始大小为 5，最大大小为 10，任务队列容量为 100
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
        // 向线程池提交 2 个任务

    *//*    for (User user : list) {
            executor.execute(new ThEmail(emailUtil,user));
            executor.execute(new ThPhone(phoneUtil,user));
        }*//*

        for (int i = 0; i < 20; i++) {
            executor.execute(new ThEmail(emailUtil,user1));
            executor.execute(new ThPhone(phoneUtil,user1));
        }

        // 关闭线程池
        executor.shutdown();*/

    }







}
